<template>
  <div class="user-list">
    <!-- 这是基础数据的页面的用户列表 -->
    <div class="user-list-create">
      <el-button type="primary" size="small" @click="increase">新增</el-button>
    </div>
    <!-- 页面渲染，组件标签，不能是html标签，否则无法渲染 -->
    <tables :tableData="tableData" :params="params" @dels="dels" :page="pages">

      <!-- 插槽，常用的有匿名插槽和具名插槽。匿名插槽是不需要绑定name属性
      在使用过程当中，template上绑定v-slot即可
      具名插槽：绑定name 属性，然后通过tempalte v-slot:name值，即可以使用
       -->
      <template v-slot:rightBtn="row">
        <el-button type="text" @click="edit(row)">编辑</el-button>
      </template>
    </tables>
    <dialogs :headerContent="infos" :dialogVisible="dialogVisible" @changeVisible="changeVisible">
      <template v-slot:content>
        <div>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="用户名" prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option label="女" value="女"></el-option>
                <el-option label="男" value="男"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input type="number" v-model.number="form.age"></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit('form')">确定</el-button>
              <el-button @click="cancel">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </dialogs>
  </div>
</template>
<script>
import Tables from "@/components/Table/Table.vue";
import Dialogs from "@/components/Dialog/Dialog.vue";
import request from "@/utils/request"; // 引入axios 
export default {
  components: {
    Tables,
    Dialogs,
  },
  data() {
    return {
      tableData: [],
      params: [
        {
          key: "name", // 后端给的接口文档中要现实的页面的字段
          value: "姓名",
        },
        {
          key: "age",
          value: "年龄",
        },
        {
          key: "sex",
          value: "性别",
        },
        {
          key: "address",
          value: "地址",
        },
      ],
      infos: "新增",
      form: {
        name: '',
        age: '',
        sex: "男",
        address: ''
      },
      rules: {
        name: [
          {message: '请输入用户名',required: true,trigger: 'blur'}
        ],
        age: [
          {message: '请输入年龄',required: true,trigger: 'blur'}
        ],
        address: [
          {message: '请输入地址',required: true,trigger: 'blur'}
        ]
      },
      dialogVisible: false,
      formNew: {},
      pages: {
        pageSize: 1,
        size: 10,
        total: 0
      },
      currentForm: {}
    };
  },
  mounted() {
    //  在mounted 当中重置了form表单，然后，在新增和删除的时候，可以重置form表单。
    this.currentForm = Object.assign({},this.form)
    this.getList()
  },
  methods: {
    getList() {
      request.post(`/user/list`,this.pages).then(res => {
        this.tableData = res.data.data.data;
        // 这里的pages 对象里边取的是返回值
        this.pages = {
          pageSize: res.data.data.pageSize,
          size: res.data.data.size,
          total: res.data.data.total,
        }
      })
    },
    // 提交（新增/ 修改）
    onSubmit(formName) {
      // 另一种校验方式即每一个字段都用if 判断，判断是否为空
      // if(!this.form.name) {
      //   this.$message({
      //     type: 'warning',
      //     message: '用户名不能为空'
      //   })
      //   return;
      // }
      let url = '/user/create'
      if(this.form.id) {
        url = '/user/update' //修改
      }
      // 根据rules 中定义的字段是否必填，用valid 来校验
      this.$refs[formName].validate((valid) => {
        console.log(valid,120)
        if (valid) {
          request.post(url,this.form).then(res => {
            console.log(res,120)
            if(res.data.code == 200) {
              this.$message({
                type: 'success',
                message: res.data.messgae
              })
              this.dialogVisible = false;
              this.getList()
            }
          })
        }
      })
      
    },
    // 新增
    increase() {
      this.infos = "新增";
      // 判断
      // if(Object.keys(this.formNew).length) { // ?????
        this.form = Object.assign({},this.currentForm)
      // }
      this.dialogVisible = true;
    },
    cancel() {
      this.dialogVisible = false;
    },
    // 接收子组件传值的参数
    changeVisible(val) {
      this.dialogVisible = false;
    },
    // 编辑
    edit(row) {
      this.infos = "编辑";
      this.formNew = Object.assign({},this.form);
      this.form = Object.assign({},row.data) // 深拷贝列表数据，到弹框中的form
      this.dialogVisible = true;
    },
    // 删除
    dels(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deletes(row)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    deletes(row) {
      request.post('/user/delete',{id:row.id}).then((res)=> {
        if(res.data.code == 200) {
          this.$message({
            type: 'success',
            message: '删除成功'
          }); 
          this.getList()
        }
      })
    }
  }
};
</script>
<style lang="scss" scoped>
// 样式嵌套不要超过3层，只用一些基础语法
// &  >
.user-list-create {
  margin-bottom: 10px;
}
</style>
